package com.zyj

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.content.res.ResourcesCompat
import com.dawn.kotlinbasedemo.R

/**
 * @author : zhaoyanjun
 * @time : 2022/3/15
 * @desc :
 */
class MyView(context: Context, attrs: AttributeSet?) : View(context, attrs) {

    private val paint = Paint()
    private val radius = 300f

    init {
        paint.isAntiAlias = true //抗锯齿
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val startX = width / 2f
        val startY = height / 2f

        //绘制圆环
        paint.color = Color.parseColor("#dddddd")
        paint.strokeWidth = 30f
        paint.style = Paint.Style.STROKE
        canvas.drawCircle(startX, startY, radius, paint)

        //绘制弧形
        paint.color = Color.RED
        paint.strokeCap = Paint.Cap.ROUND
        val rectF = RectF(startX - radius, startY - radius, startX + radius, startY + radius)
        canvas.drawArc(rectF, -90f, 225f, false, paint)

        //绘制文字
        val content = "ababcfp"
        paint.textSize = 80f
        paint.style = Paint.Style.FILL
        //居中绘制
        paint.textAlign = Paint.Align.CENTER
        //加载字体
        paint.typeface = ResourcesCompat.getFont(context, R.font.fangzheng)

        //获取文字的的边界，这个编辑基于文字baseline
        val bounds = Rect()
        paint.getTextBounds(content, 0, content.length, bounds)
        //获取边界的高度
        val boundHeight = bounds.bottom - bounds.top
        canvas.drawText(content, startX, startY + boundHeight / 2, paint)

        //方式二
        val fontMetrics = paint.fontMetrics
        val boundHeight2 = fontMetrics.descent - fontMetrics.ascent
        canvas.drawText(content, startX, startY + boundHeight2 / 2, paint)

        paint.textAlign = Paint.Align.LEFT
        val fontMetrics2 = paint.fontMetrics
        val height = fontMetrics2.top
        canvas.drawText("ababfgq", 0f, 0f - height, paint)
    }
}